import React, { useState, useEffect } from "react"
import styles from "./index.module.scss"
import { NavLink, useLocation, useNavigate } from "react-router-dom"
import { Form, Input, Button, Upload, Radio, message } from "antd"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-react"
import Channel from "../../components/Channel"
import { PlusOutlined } from "@ant-design/icons"
import {
  publishSrticle,
  getArticlesDetail,
  editArticles
} from "../../store/action"
import { useDispatch } from "react-redux"
function Article() {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  // 获取表单实例
  const [form] = Form.useForm()
  // 用于获取路由参数
  const location = useLocation()
  // 单选
  const [radioValue, setRadioValue] = useState(1)
  // 上传图片
  const [fileList, setFileList] = useState([])
  const onUploadChange = (value) => {
    console.log(value)
    const newFileList = value.fileList.map((file) => {
      if (file.response) {
        // 有响应数据的时候
        return {
          url: file.response.data.url
        }
      }
      // 如果还没有 response 说明，图片还在上传过程中
      // 此时，为了让后续图片上传完成后，能够正确拿到 图片地址 ，所以，此处需要暂时将 file 返回
      // 如果不把 file 返回，会导致 onChange 不会重复执行，这样，将来无法拿到 图片上传成功时 的图片数据了
      return file
    })
    setFileList(newFileList)
  }
  // 更改上传图片个数
  const changeRadio = (e) => {
    const count = e.target.value
    setRadioValue(count)

    if (count === 1) {
      const current = fileList[0] ? [fileList[0]] : []
      setFileList(current)
    } else if (count === 0) {
      setFileList([])
    }
  }

  // 富文本编辑器
  const [editor, setEditor] = useState(null) // 存储 editor 实例
  const [html, setHtml] = useState("14") // 编辑器内容
  const toolbarConfig = {}
  const editorConfig = {
    placeholder: "<p>请输入文章内容</p>"
  }
  // 及时销毁 editor ，重要！
  // useEffect(() => {
  //   return () => {
  //     if (editor == null) editor.destroy()
  //     setEditor(null)
  //   }
  // }, [editor])
  // 获取文章详情id
  const id = location.search.substr(4)
  // 有id则为编辑,否则为发布
  const isEdit = Boolean(id)
  useEffect(() => {
    if (!isEdit) return
    const getDetail = async () => {
      const { data } = await dispatch(getArticlesDetail(id))
      const { title, channel_id, content, cover } = data
      // 回显数据
      form.setFieldsValue({
        title,
        content,
        radio: cover.type,
        channel: channel_id
      })
      setHtml(content)
      const newFileList = cover.images.map((item) => ({ url: item }))
      setFileList(newFileList)
    }
    getDetail()
    // eslint-disable-next-line
  }, [dispatch, id, isEdit])

  // 发表文章
  const onSearch = async (value, msg = "发表成功", draft) => {
    const { title, channel, radio } = value
    // 判断封面数量与所选类型是否匹配
    if (radio !== fileList.length) {
      return message.error("封面数量与所选类型不匹配")
    }

    const formValue = {
      title,
      content: html,
      cover: {
        type: radio,
        images: fileList.map((item) => item.url)
      },
      channel_id: channel
    }
    // 判断是编辑还是发表
    if (!isEdit) {
      // 发表
      if (draft) {
        // 是否存为草稿
        formValue.draft = draft
      }
      // 发表文章
      await dispatch(publishSrticle(formValue))
      message.success(msg, 1, () => {
        navigate("/home/content")
      })
    } else {
      formValue.id = id
      dispatch(editArticles(formValue))
      message.success("编辑成功", 1, () => {
        navigate("/home/content")
      })
    }
  }
  // 存入草稿
  const saveDraft = async () => {
    try {
      // 触发表单验证
      const values = await form.validateFields()
      onSearch(values, "存入草稿成功", true)
    } catch (e) {}
  }
  const remove = (file) => {
    console.log(file)
  }
  return (
    <div className={styles.article}>
      <div className={styles.article_title}>
        <span>
          <NavLink to="/home">首页</NavLink>
        </span>
        <span className={styles.middle}>&gt;</span>
        <span>发布文章</span>
      </div>
      <div className={styles.article_conent}>
        <Form
          form={form}
          scrollToFirstError
          onFinish={onSearch}
          name="basic"
          labelCol={{
            span: 4
          }}
          wrapperCol={{
            span: 16
          }}
          autoComplete="off"
          initialValues={{
            radio: 1
          }}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: "请输入文章标题"
              }
            ]}
          >
            <Input placeholder="请输入文章标题" style={{ width: "400px" }} />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel"
            rules={[
              {
                required: true,
                message: "请选择文章频道"
              }
            ]}
          >
            <Channel width={400}></Channel>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="radio">
              <Radio.Group
                style={{ width: "400px", marginTop: 4 }}
                onChange={changeRadio}
              >
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {radioValue !== 0 && (
              // <Form.Item>
              <div style={{ marginTop: 28 }}>
                <Upload
                  name="image"
                  listType="picture-card"
                  action="http://geek.itheima.net/v1_0/upload"
                  fileList={fileList}
                  maxCount={radioValue}
                  multiple={fileList.length === 3}
                  onPreview={() => {}}
                  onChange={onUploadChange}
                  onRemove={remove}
                >
                  {fileList.length < radioValue ? (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}></div>
                    </div>
                  ) : null}
                </Upload>
              </div>
              // </Form.Item>
            )}
          </Form.Item>

          <Form.Item label="内容">
            <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ borderBottom: "1px solid #ccc" }}
              />

              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor) => setHtml(editor.getHtml())}
                mode="default"
                style={{ height: "300px" }}
              ></Editor>
            </div>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 4,
              span: 16
            }}
          >
            <Button type="primary" htmlType="submit" size="large">
              {isEdit ? "编辑文章" : "发布文章"}
            </Button>

            <Button onClick={saveDraft} size="large">
              存入草稿
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Article
